package client.comm.commlib

import android.content.Context
import android.content.res.Resources
import android.util.DisplayMetrics
import android.util.Log
import android.util.TypedValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.io.*


inline fun Float.toDp(): Int {
    val tmp = this
    ContextProvider.get().activity?.run {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            tmp,
            this.resources.displayMetrics
        ).toInt()
    }

    return tmp.toInt()
}

suspend fun out_time(block: suspend () -> Unit) {
    withTimeout(15000) {
        block?.invoke()
    }
}

fun dipToPx(resources: Resources, dp: Float): Float {
    val metrics = resources.displayMetrics
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics)
}

fun pxTodip(resources: Resources, pxValue: Float): Int {
    val scale = resources.displayMetrics.density
    return (pxValue / scale + 0.5f).toInt()
}


inline suspend fun <reified T : Serializable> Serializable.read(): T? {
    return withContext(Dispatchers.IO) {
        var t: T? = null
        ContextProvider.get().activity?.run {
            var fis: FileInputStream? = null
            var ois: ObjectInputStream? = null
            try {
                val file = File(filesDir, "${T::class.java.name}")
                if (file.exists()) {
                    fis = openFileInput("${T::class.java.name}")
                    ois = ObjectInputStream(fis)
                    t = ois.readObject() as T
                    fis.close()
                    ois.close()
                } else {
                    Log.e("EEE", "文件不存在")
                }
            } catch (e: Exception) {
                Log.e("EEE", e.message, e)
            }
        }
        t
    }
}

fun getScreenWidth(context: Context): Int {
    return context.resources.displayMetrics.widthPixels
}

fun getScreenHeight(context: Context): Int {
    return context.resources.displayMetrics.heightPixels
}

inline suspend fun <reified T : Serializable> Serializable.write(t: T): Boolean {
    return if (t == null) false else withContext(Dispatchers.IO) {
        var b: Boolean = false
        ContextProvider.get().activity?.run {
            try {
                val outStream =
                    openFileOutput("${T::class.java.name}", Context.MODE_PRIVATE)
                val oos = ObjectOutputStream(outStream)
                oos.writeObject(t)
                oos.flush()
                oos.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        b
    }
}